package com.ljj;

import java.util.*;

public class Value {
    private String path;
    private Map<String, List<Value>> innerValue = new HashMap<String, List<Value>>();
    private String textValue;
    private Value parent;

    public Value(String path, Value parent) {
        this.path = path;
        this.parent = parent;
    }

    public Value getParent() {
        return parent;
    }

    public String getPath() {
        return path;
    }

    /**
     * 设置内部值
     *
     * @param path
     * @param o
     */
    public void setValue(String path, Value o) {
        List<Value> vNode = innerValue.get(path);
        if (vNode == null) {
            vNode = new ArrayList<Value>();
            innerValue.put(path, vNode);
        }
        vNode.add(o);
    }

    /**
     * 设置文本值
     *
     * @param txtValue
     */
    public void setValue(String txtValue) {
        this.textValue = txtValue;
    }

    /**
     * 获得文本值
     *
     * @return
     */
    public Optional<String> getTxtValue() {
        if (this.textValue != null) {
            return Optional.of(this.textValue);
        } else {
            return Optional.empty();
        }
    }

    /**
     * 获得内部值对象列表
     *
     * @param path
     * @return
     */
    public Optional<List<Value>> getValues(String path) {
        if (innerValue.get(path) == null) {
            return Optional.empty();
        }
        if (innerValue.get(path).size() != 0) {
            return Optional.of(innerValue.get(path));
        } else {
            return Optional.empty();
        }
    }

    /**
     * 获得单一的内部值对象
     *
     * @param path
     * @return
     */
    public Optional<Value> getValue(String path) {
        if (innerValue.get(path) == null) {
            return Optional.empty();
        }
        if (innerValue.get(path).size() == 1) {
            return Optional.of(innerValue.get(path).get(0));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public String toString() {
        return "Value{" +
                "path='" + path + '\'' +
                ", textValue='" + textValue + '\'' +
                ", parent=" + parent +
                '}';
    }
}
